//
//  HttpRequest.swift
//
//
//  Created by Daniel on 2018/4/3.
//  Copyright © 2018年 shen_h. All rights reserved.
//

import UIKit
import Alamofire

typealias postParameters = [String:Any]

enum MethodType {
    case get
    case post
}

class HttpRequest {
    
    class func requestData(_ type : MethodType, URLString : String, parameters : postParameters? = nil, finishedCallback :  @escaping (_ result : postParameters) -> ()) {
        
        // 获取类型
        let method = type == .get ? HTTPMethod.get : HTTPMethod.post
        let manager = Alamofire.SessionManager.default
        manager.session.configuration.timeoutIntervalForRequest = 10
        let url = (Api.root.rawValue + URLString).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        
        var value = ""
        if Utils.isLogined() {
            value = Utils.getUserDefaulsFor(key: "token") as! String
        }
        let header = ["authorization":value]
        
        manager.request(URL.init(string: url!)!, method: method, parameters: parameters, encoding: URLEncoding.init(), headers: header).responseJSON { (response) in
            // 获取结果
            switch response.result {
            case .success(_):
                if let value = response.result.value as? postParameters{
                    print("\(URLString) == \(value)")
                    if value["msg"] as! String != "success" {
                        if value["isLogin"] != nil {
                            NotificationCenter.default.post(name: NSNotification.Name(rawValue:"needLogin"), object: ["notice":value["data"] as! String])
                        }
                        finishedCallback(value)
                    }else{
                       finishedCallback(value)
                    }
                }
            case .failure(_):
                PKhud.hiden()
                break
                
            }
        }
        
//        manager.request(URL.init(string: url!)!, method: method, parameters: requestParameter).responseJSON { (response) in
//
//            // 获取结果
//            guard let result = response.result.value else {
//                print(response.result.error!)
//                return
//            }
//            print("\(URLString) == \(result)")
//
//            finishedCallback(result as! postParameters)
//        }
    }
    
    class func uploadImage(image: UIImage,finishedCallback :  @escaping (_ result : postParameters) -> ()){
        let imageData = UIImageJPEGRepresentation(image, 0.5)
        let url = Api.root.rawValue + "/upload"
        print(url)
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                //采用post表单上传
                let name = Date().dateNowAsString("yyyy-MM-dd HH:mm") + ".jpeg"
                multipartFormData.append(imageData!, withName: "file", fileName: name, mimeType: "image/jpeg")
                
        },to:url ,encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                
                upload.responseJSON { response in
                    
                    guard let result = response.result.value else { return }
                    print("json:\(result)")
                    finishedCallback(result as! postParameters)
                }
                //获取上传进度
                upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
                    print("图片上传进度: \(progress.fractionCompleted)")
                }
            case .failure(let encodingError):
                //打印连接失败原因
                print(encodingError)
            }
        })
    }
    
}









